﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trie;

namespace BoggleSolver
{
    class Program
    {
        static Trie.Trie trie = null;
        static char[,] input = new char[,]{
        {'g','i','z'},
                       {'u','e','k'},
                       {'q','s','e'}};

        static bool[,] visibility = new bool[,] {
            {false, false, false},
            {false, false, false},
            {false, false, false}};

        static int[] rowArray = new int[8] { 0, -1, -1, -1, 0, 1, 1, 1 };
        static int[] colArray = new int[8] { -1, -1, 0, 1, 1, 1, 0, -1 };

        static void Main(string[] args)
        {
            trie = new Trie.Trie();
            DateTime st = DateTime.Now;
            for (int i = 0; i < input.GetLength(0); i++)
            {
                for (int j = 0; j < input.GetLength(1); j++)
                {
                    Process(input[i,j].ToString(), i, j);
                    ResetVisibility();
                }
            }
            Console.WriteLine(DateTime.Now.Subtract(st));
            Console.ReadLine();
        }

        private static void ResetVisibility()
        {
            for (int i = 0; i < visibility.GetLength(0); i++)
            {
                for (int j = 0; j < visibility.GetLength(1); j++)
                {
                    visibility[i, j] = false;
                }
            }
        }

        static void Process(string data, int i, int j)
        {
            if (visibility[i, j])
                return;
            visibility[i, j] = true;
            for (int k = 0; k < rowArray.Length; k++)
            {
                if (i + rowArray[k] >= 0 && i + rowArray[k] < input.GetLength(0) &&
                    j + colArray[k] >= 0 && j + colArray[k] < input.GetLength(1) && !visibility[i + rowArray[k], j + colArray[k]])
                {
                    string newData = data + input[i + rowArray[k], j + colArray[k]];
                    var result = trie.Search(newData.ToCharArray());
                    if (result.Count == 0)
                        continue;
                    else
                    {
                        if (result.Where(t => t.Word == newData).FirstOrDefault() != null)
                            Console.WriteLine(newData);
                        Process(newData, i + rowArray[k], j + colArray[k]);
                    }
                }
            }
        }
    }
}
